﻿//**********************************************************
//Copyright(C)2010 By 波特商网公司 版权所有。
//
//文件名：
//文件功能：日志记录器
//
//创建标识：齐李平 || 2011-06-13
//
//修改标识：
//修改描述：
//**********************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace Hmc.IM.Common
{
    /// <summary>
    /// 错误类型
    /// </summary>
    public enum LogType
    {
        /// <summary>
        /// 致命错误
        /// </summary>
        FATAL,
        /// <summary>
        /// 错误
        /// </summary>
        ERROR,
        /// <summary>
        /// 警告
        /// </summary>
        WARN,
        /// <summary>
        /// 信息
        /// </summary>
        INFO,
        /// <summary>
        /// 调试
        /// </summary>
        DEBUG,
    }

    /// <summary>
    /// 错误日志记录帮助类
    /// </summary>
    public class Logger
    {
        private static object lockobj = new object();

        /// <summary>
        /// 异常日志记录
        /// </summary>
        /// <param name="exception">异常实例</param>
        public static void Write(Exception exception)
        {
            Write(LogType.WARN, exception);
        }

        /// <summary>
        /// 异常日志记录
        /// </summary>
        /// <param name="logType">异常类型</param>
        /// <param name="exception">异常实例</param>
        public static void Write(LogType logType, Exception exception)
        {
            lock (lockobj)
            {
                FileStream fs = null;
                StreamWriter sw;

                //程序运行路径
                string strFilePath = LogPath();

                //日志名
                string fileName = "exception" + DateTime.Now.ToString("yyyyMMdd");

                //日志完整路径
                string strPath = strFilePath.ToString() + fileName.ToString() + ".log";
                //是否作出新的标签
                bool bolFlg = false;

                //判断文件是否存在
                if (!File.Exists(strPath))
                {
                    if (!Directory.Exists(strFilePath))
                    {
                        Directory.CreateDirectory(strFilePath);
                    }

                    bolFlg = true;
                    //创建文件
                    fs = File.Create(strPath);
                    File.SetAttributes(strPath, FileAttributes.Normal);

                    //实例化StreamWriter
                    sw = new StreamWriter(fs);
                    //文件头
                    sw.WriteLine(string.Format("Create at: {0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                }
                else
                {
                    sw = File.AppendText(strPath);
                }

                //声明实例化StackTrace,获得即时跟踪信息
                StackTrace stacktrace = new StackTrace(exception, true);
                if (stacktrace.FrameCount < 1)
                {
                    sw.Close();
                    if (bolFlg.Equals(true)) fs.Close();
                    return;
                }
                string logline = "{0} : [{1}] : [Source File]{2} : [Event Name]{3} : [Line error]{4} : [Description]{5} ";
                StackFrame stackframe = stacktrace.GetFrame(0);

                //组合日志内容
                StringBuilder strBuilder = new StringBuilder();
                strBuilder.Append("\r\n");
                strBuilder.Append("[BeginLogEx] \r\n");

                strBuilder.AppendFormat(logline, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), logType.ToString(), stackframe.GetFileName(), stackframe.GetMethod().Name, stackframe.GetFileLineNumber(), exception.Message);
                strBuilder.Append("\r\n");
                strBuilder.Append("[Exceptions] \r\n");

                string ExceptionLineFormat = "{0}: {1} \r\n";
                Exception tempE = exception;
                while (tempE != null)
                {
                    strBuilder.AppendFormat(ExceptionLineFormat, tempE.GetType().Name, tempE.Message);
                    tempE = tempE.InnerException;
                }
                strBuilder.Append("[BeginStackTrace]\r\n");
                strBuilder.Append(exception.StackTrace);
                strBuilder.Append("\r\n");
                strBuilder.Append("[EndStackTrace]\r\n");
                strBuilder.Append("[EndLogEx] \r\n");

                //写入日志内容
                sw.WriteLine(strBuilder.ToString());
                sw.WriteLine("------------------------------------------------------------------\n");
                sw.Flush();
                sw.Close();
                if (bolFlg.Equals(true))
                {
                    fs.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logType"></param>
        /// <param name="message"></param>
        public static void Write(LogType logType, string message)
        {
            lock (lockobj)
            {
                FileStream fs = null;
                StreamWriter sw;

                //程序运行路径
                string strFilePath = LogPath();

                //日志名
                string fileName = logType.ToString() + "log";// DateTime.Now.ToString("yyyyMMdd");

                //日志完整路径
                string strPath = strFilePath.ToString() + fileName.ToString() + ".log";
                //是否作出新的标签
                bool bolFlg = false;

                //判断文件是否存在
                if (!File.Exists(strPath))
                {
                    if (!Directory.Exists(strFilePath))
                    {
                        Directory.CreateDirectory(strFilePath);
                    }
                    bolFlg = true;
                    //创建文件
                    fs = File.Create(strPath);
                    File.SetAttributes(strPath, FileAttributes.Normal);

                    //实例化StreamWriter
                    sw = new StreamWriter(fs);
                    //文件头
                    sw.WriteLine(string.Format("Create at: {0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                }
                else
                {
                    sw = File.AppendText(strPath);
                }

                string logline = "{0} : {1}  ";

                //组合日志内容
                StringBuilder strBuilder = new StringBuilder();
                //strBuilder.Append("\r\n");
                //strBuilder.Append("[BeginLog] \r\n");

                strBuilder.AppendFormat(logline, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), message);
                //strBuilder.Append("\r\n");
                //strBuilder.Append("[EndLog] \r\n");

                //写入日志内容
                sw.WriteLine(strBuilder.ToString());
                sw.WriteLine("------------------------------------------------------------------\n");
                sw.Flush();
                sw.Close();
                if (bolFlg.Equals(true))
                {
                    fs.Close();
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        public static void Write(string message)
        {
            lock (lockobj)
            {
                FileStream fs = null;
                StreamWriter sw;

                //程序运行路径
                string strFilePath = LogPath();

                //日志名
                string fileName = "Log";// DateTime.Now.ToString("yyyyMMdd");

                //日志完整路径
                string strPath = strFilePath.ToString() + fileName.ToString() + ".log";
                //是否作出新的标签
                bool bolFlg = false;

                //判断文件是否存在
                if (!File.Exists(strPath))
                {
                    if (!Directory.Exists(strFilePath))
                    {
                        Directory.CreateDirectory(strFilePath);
                    }
                    bolFlg = true;
                    //创建文件
                    fs = File.Create(strPath);
                    File.SetAttributes(strPath, FileAttributes.Normal);

                    //实例化StreamWriter
                    sw = new StreamWriter(fs);
                    //文件头
                    sw.WriteLine(string.Format("Create at: {0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                }
                else
                {
                    sw = File.AppendText(strPath);
                }

                string logline = "{0} : [{1}] : [UserId]{2} : [UserName]{3} : [Business]{4} : [Description]{5} ";

                //组合日志内容
                StringBuilder strBuilder = new StringBuilder();
                strBuilder.Append("\r\n");
                strBuilder.Append("[BeginLog] \r\n");

                strBuilder.AppendFormat(logline, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), "自动服务", "", "", "", message);
                strBuilder.Append("\r\n");
                strBuilder.Append("[EndLog] \r\n");

                //写入日志内容
                sw.WriteLine(strBuilder.ToString());
                sw.WriteLine("------------------------------------------------------------------\n");
                sw.Flush();
                sw.Close();
                if (bolFlg.Equals(true))
                {
                    fs.Close();
                }
            }
        }

        /// <summary>
        /// 程序运行目录
        /// </summary>
        /// <returns></returns>
        private static string LogPath()
        {
            return System.IO.Directory.GetCurrentDirectory() + @"\log\";
        }
    }
}
